package com.lei.lib_croe.http.token;

import com.blankj.utilcode.util.SPUtils;
import com.lei.lib_croe.http.Api;
import com.lei.lib_croe.http.factory.RetrofiType;
import com.lei.lib_croe.http.factory.RetrofitFactory;

import java.io.IOException;
import java.util.Objects;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

public class ToKenInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Response response = chain.proceed(request);
        if (SPUtils.getInstance().contains(Contants.TOKEN_KEY)){
            response = chain.proceed(addToken(request,SPUtils.getInstance().getString(Contants.TOKEN_KEY)));
        }else {
            response = chain.proceed(request);
        }
        if (response.code() == Contants.TOKEN_NON){
            //获取token
            String newToken = createNewToken();
            SPUtils.getInstance().put(Contants.TOKEN_KEY,newToken);
            response = chain.proceed(addToken(request,newToken));
        }
        return response;
    }

    private String createNewToken() throws IOException {
        return Objects.requireNonNull(RetrofitFactory
                .getInstance()
                .createRetrofit(RetrofiType.NETWORK)
                .getRerofit()
                .create(Api.class))
                .token("password","b519c1671bf11916a14715811911e1421f71661701ce1ba1","")
                .execute()
                .body()
                .access_token;
    }

    private Request addToken(Request request,String token) {
        return request.newBuilder().addHeader("Authorization","bearer "+token).build();
    }
}
